package com.peng.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.order.entity.Order;
import com.peng.order.service.OrderService;
import com.peng.utils.JwtUtils;
import com.peng.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Dengp
 * @since 2022-06-24
 */
@RestController
@RequestMapping("/order/order")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    //生成订单并返回订单编号
    @PostMapping("/saveOrder/{courseId}")
    public Result saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        String orderId =orderService.saveOrder(courseId,userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId",orderId);
        return Result.ok().data(map);
    }

    //根据课程id和用户id查询订单是否完成
    @GetMapping("/getCourseIdAnduserIdByOrder/{courseId}")
    public Result getCourseIdAnduserIdByOrder(@PathVariable String courseId,HttpServletRequest request){
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId,courseId);
        queryWrapper.eq(Order::getMemberId,userId);
        queryWrapper.eq(Order::getStatus,1);
        int count = orderService.count(queryWrapper);
        HashMap<String, Boolean> map = new HashMap<>();
        if (count>0){
            map.put("isBuy",true);
            return Result.ok().data(map);
        }
        map.put("isBuy",false);
        return Result.ok().data(map);

    }

    //根据订单号查询订单信息
    @GetMapping("/getOrderInfo/{id}")
    public  Result getOrderInfo(@PathVariable String id){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo,id);
        Order one = orderService.getOne(queryWrapper);
        return Result.ok().data(one);
    }
}

